package com.example.controller;

import com.example.controller.web.FileController;
import com.example.entity.trace.dto.DescTraceDTO;
import com.example.mapper.dao.QRDao;
import com.example.service.QRService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.example.common.Result;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api/qr")
public class QRController {

    @Autowired
    private QRService qrService;

    @Resource
    private QRDao qrDao;

    @Resource
    private FileController fileController;

    @Value("${tencent.cos.accessKey}")
    private String accessKey;

    @Value("${tencent.cos.secretKey}")
    private String secretKey;

    @Value("${tencent.cos.region}")
    private String region;

    @Value("${tencent.cos.bucket}")
    private String bucket;

    @Value("${fileBaseUrl}")
    private String fileBaseUrl;

    @GetMapping("/GetTraceDesc")
    public Result GetTraceDesc(String traceUid){
        return Result.success(qrService.GetTraceDesc(traceUid));
    }

    @GetMapping("/GetTraceUid")
    public Result GetTraceUid(String itemId){
        return Result.success(qrDao.GetTraceUid(itemId));
    }

    @PostMapping("/generate-code")
    public ResponseEntity<String> generateCode(String itemId) {
        String codeValue = UUID.randomUUID().toString();


        // 生成二维码图片并保存到本地
        String imagePath = generateQRCodeImage(codeValue);

        int num= qrDao.insertTrace(codeValue,itemId,imagePath);
        if(num>0){
            return ResponseEntity.ok("生成成功");
        }

        return ResponseEntity.ok(imagePath);
    }

    // 生成二维码图片并返回本地路径
    private String generateQRCodeImage(String traceUid) {
        // 配置二维码参数
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix;
        try {
            // 生成二维码内容为URL
            String url = "https://www.chessunyan.asia/qr/" + traceUid;
            bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, 300, 300);
        } catch (WriterException e) {
            throw new RuntimeException("QR生成失败", e);
        }

        // 生成图片临时文件
        String fileName = traceUid + ".png";
        String tempDirectory=System.getProperty("java.io.tmpdir");
        String tempFilePath=tempDirectory+File.separator+fileName;
        File tempQRCodeFile=new File(tempFilePath);

        // 将二维码生成为图片并保存到临时文件
        try {
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(tempFilePath));
        } catch (IOException e) {
            throw new RuntimeException("保存二维码图片失败", e);
        }

        String cosFilePath=uploadToCOS(tempQRCodeFile,fileName);

        tempQRCodeFile.delete();

        return cosFilePath; // 返回本地文件路径
    }

    private String uploadToCOS(File file, String fileName) {
        System.out.println(fileName);
        // 指定要上传到 COS 上对象键
        String key = "/qr/" + fileName; // 根据需要设置路径
        try {
            // 初始化用户身份信息(secretId, secretKey)
            BasicCOSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
            // 设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(region));
            // 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);

            //创建ObjectMetadata
            ObjectMetadata metadata=new ObjectMetadata();
            metadata.setContentLength(file.length());
            // 创建PutObjectRequest对象
            InputStream inputStream=new FileInputStream(file);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key,inputStream, metadata);
            // 上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            // 关闭客户端
            cosClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传到COS失败";
        }
        String url = fileBaseUrl + key;
        return url;
    }

}
